package com.jrx.anytxn.param.transaction.job.billCompare.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransInnerSummary;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransInnerSummaryMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.transaction.config.BillCompareConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlGlInterfaceInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlRefundLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlTransactionInfoMapper;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 外部对账-txn内部交易流水汇总job
 *
 * @author : zcc
 * 2020/11/30
 */
@Configuration
public class ThirdBillSummaryReadConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(ThirdBillSummaryReadConfiguration.class);

    @Resource
    public JobBuilderFactory jobBuilderFactory;
    @Resource
    public StepBuilderFactory stepBuilderFactory;
    @Resource
    private ExtTlBillTransInnerSummaryMapper extTlBillTransInnerSummaryMapper;
    @Resource
    private ISegmentService iSegmentService;
    @Resource
    private IOrganizationTableService organizationTableService;
    @Resource
    private BillCompareConfig billCompareConfig;
    @Resource
    private ExtAmLoanMainInfoMapper extAmLoanMainInfoMapper;
    @Resource
    private ExtTlGlInterfaceInfoMapper extTlGlInterfaceInfoMapper;
    @Resource
    private ExtTlPaymentLogMapper extTlPaymentLogMapper;
    @Resource
    private ExtTlRefundLogMapper extTlRefundLogMapper;

    @Bean
    public Job thirdBillSummaryReadJob() {
        return jobBuilderFactory.get("thirdBillSummaryReadJob")
                .start(thirdBillSummaryReadStep())
                .build();
    }

    @Bean
    public Step thirdBillSummaryReadStep() {
        return stepBuilderFactory.get("thirdBillSummaryReadStep")
                .tasklet(thirdBillSummaryReadTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet thirdBillSummaryReadTasklet() {
        return (stepContribution, chunkContext) -> {
/*
            PrOrganizationTable organization = organizationTableService.findByOrgIdForBatch(TransBizConstant.XIB_ORG_NUMBER);
            // 设置指定对账日期
            Date today = billCompareConfig.getToday();
            if (Objects.nonNull(today)) {
                organization.setToday(today);
            }
            Date businessDate = organization.getToday();
            String busDate = DateUtils.format(businessDate);
            logger.info("外部对账-txn内部交易流水汇总开始。。。,业务日期{}", busDate);
            // 租户id
            String tenantId = organization.getTenantId();
            List<TlBillTransInnerSummary> tlBillTransInnerSummaryList = new ArrayList<>();

            //清除当日对账数据，支持重跑
            extTlBillTransInnerSummaryMapper.deleteByFromAndBusDateAndThirdChannel(billCompareConfig.getDataFrom(), businessDate, billCompareConfig.getThirdChannel());

            //消费成功总金额
            BigDecimal totalAmount = extAmLoanMainInfoMapper.sumByBusinessDateAndLoanType(tenantId, businessDate, TransBizConstant.LOAN_TYPE_4, billCompareConfig.getThirdChannel());
            BigDecimal glAmount = extAmLoanMainInfoMapper.sumByBusinessDateAndLoanTypeAndTxnCode(tenantId, businessDate, TransBizConstant.LOAN_TYPE_4, "T54000", billCompareConfig.getThirdChannel());
            totalAmount = totalAmount.add(glAmount);
            //消费成功总笔数
            Integer totalCount = extAmLoanMainInfoMapper.countByBusinessDateAndLoanType(tenantId, businessDate, TransBizConstant.LOAN_TYPE_4, billCompareConfig.getThirdChannel());

            tlBillTransInnerSummaryList.add(buildTransInnerSumList(organization, Constant.TRANSACTION_TYPE_XF, totalCount, totalAmount, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S));

            //取消成功总笔数()
            Integer totalRevocationCount = extTlGlInterfaceInfoMapper.countByBusinessDateAndTxnCode(tenantId, businessDate,
                    Arrays.asList(TransBizConstant.TXN_CODE_INSTSUM_REVOCATION, TransBizConstant.TXN_CODE_MARKETING_RECOVERY_FEE),
                    billCompareConfig.getThirdChannel());
            //取消成功总金额
            BigDecimal totalRevocationAmount = extTlGlInterfaceInfoMapper.sumByBusinessDateAndTxnCode(tenantId, businessDate, Arrays.asList(TransBizConstant.TXN_CODE_INSTSUM_REVOCATION,
                    TransBizConstant.TXN_CODE_MARKETING_RECOVERY_FEE), billCompareConfig.getThirdChannel());
            tlBillTransInnerSummaryList.add(buildTransInnerSumList(organization, Constant.TRANSACTION_TYPE_CX, totalRevocationCount, totalRevocationAmount, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S));

            // 退款成功总笔数
            int totalRefundCount = extTlPaymentLogMapper.countBySumStatusAndBusinessDateAndThirdChannel(tenantId, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S, businessDate, billCompareConfig.getThirdChannel(), TransBizConstant.REPAYMENT_TYPE_REFUND);
            // 溢缴款成功笔数
            int refundCount = extTlRefundLogMapper.countBySumStatusAndBusinessDateAndThirdChannel(tenantId, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S, businessDate, billCompareConfig.getThirdChannel());
            totalRefundCount = totalRefundCount + refundCount;
            // 退款成功金额
            BigDecimal totalRefundAmount = extTlPaymentLogMapper.sumBySumStatusAndBusinessDateAndThirdChannel(tenantId, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S, businessDate, billCompareConfig.getThirdChannel(), TransBizConstant.REPAYMENT_TYPE_REFUND);
            // 溢缴款成功金额
            BigDecimal refundAmount = extTlRefundLogMapper.sumBySumStatusAndBusinessDateAndThirdChannel(tenantId, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S, businessDate, billCompareConfig.getThirdChannel());
            totalRefundAmount = totalRefundAmount.add(refundAmount);
            tlBillTransInnerSummaryList.add(buildTransInnerSumList(organization, Constant.TRANSACTION_TYPE_TK, totalRefundCount, totalRefundAmount, TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S));

            if (CollectionUtils.isNotEmpty(tlBillTransInnerSummaryList)) {
                extTlBillTransInnerSummaryMapper.insertbatch(tlBillTransInnerSummaryList);
            }

            logger.info("外部对账-txn内部交易流水汇总完成。。。,业务日期{}", busDate);*/
            return RepeatStatus.FINISHED;
        };
    }

    private TlBillTransInnerSummary buildTransInnerSumList(PrOrganizationTable organization, String transType, Integer totalCount, BigDecimal totalAmount, String innerStatus) throws SegmentException {

        TlBillTransInnerSummary tlBillTransInnerSummary = new TlBillTransInnerSummary();
        tlBillTransInnerSummary.setTenantId(organization.getTenantId());
        tlBillTransInnerSummary.setOrganizationId(organization.getOrganizationId());
        tlBillTransInnerSummary.setId(iSegmentService.getId("TlBillTransInnerSummary"));
        tlBillTransInnerSummary.setBillType(transType);
        tlBillTransInnerSummary.setBusinessDate(organization.getToday());
        tlBillTransInnerSummary.setInnerStatus(innerStatus);
        tlBillTransInnerSummary.setInnerTotalCount(totalCount == null ? 0 : totalCount);
        tlBillTransInnerSummary.setInnerTotalAmount(totalAmount == null ? BigDecimal.ZERO : totalAmount);
        tlBillTransInnerSummary.setThirdChannel(billCompareConfig.getThirdChannel());
        tlBillTransInnerSummary.setDataFrom(billCompareConfig.getDataFrom());
        tlBillTransInnerSummary.setThirdChannel(billCompareConfig.getThirdChannel());
        return tlBillTransInnerSummary;
    }

}
